<template>
  <view class="box" :style="customBoxStyle">
    <view class="tag" @tap.stop="chooseAll" :style="isAll ? customStyle : customCheckStyle">
      <text v-if="isAll">全选</text>
      <text v-else>取消</text>
    </view>
    <view
      class="tag"
      @tap.stop="click(item)"
      :style="item.checked ? customCheckStyle : customStyle"
      v-for="(item, index) in list"
      :key="index"
    >
      {{ item.label }}
    </view>
  </view>
</template>

<script>
export default {
  name: "chooseBtn",
  props: {
    // 自定义按钮样式，对象形式
    customStyle: {
      type: Object,
      default() {
        return {};
      },
    },
    customCheckStyle: {
      type: Object,
      default() {
        return {};
      },
    },
    // 自定义盒子样式，对象形式
    customBoxStyle: {
      type: Object,
      default() {
        return {};
      },
    },
    list: {
      type: Array,
      default() {
        return [];
      },
    },
    listIsAll: {
      type: Boolean,
      default() {
        return true;
      },
    },
  },
  data() {
    return {
      chooseList: [],
      isAll: true,
    };
  },
  mounted() {
    this.init();
  },
  watch: {
    listIsAll: {
      immediate: false,
      handler: function (newval) {
        if (newval) {
          this.isAll = true;
          this.init();
        } else {
          this.isAll = false;
        }
      },
    },
    list: {
      immediate: false,
      deep: true,
      handler: function (newval) {
        this.init();
      },
    },
  },
  methods: {
    init() {
      let arr = [];
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].checked) {
          arr.push(this.list[i]);
        }
      }
      if (arr.length === this.list.length) {
        this.isAll = false;
      } else {
        this.isAll = true;
      }
    },
    click(e) {
      e.checked = !e.checked;
      let arr = [];
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].checked) {
          arr.push(this.list[i]);
        }
      }
      if (arr.length !== this.list.length) {
        this.isAll = true;
      }
      if (arr.length === this.list.length) {
        this.isAll = false;
      }
      this.chooseList = arr;
      this.$emit("click", this.chooseList);
    },
    chooseAll() {
      this.isAll = !this.isAll;
      if (!this.isAll) {
        this.chooseList = this.list;
      } else {
        this.chooseList = [];
      }
      if (this.list.length > 0) {
        for (let i = 0; i < this.list.length; i++) {
          this.list[i].checked = !this.isAll;
        }
      }
      this.$emit("click", this.chooseList);
      this.$emit("reset");
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 100%;
  .tag {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 1rem;
  }
}
</style>
